#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 7、一维数组 转 二维数组二维数组 转一维数组(堆内存)

// 一维数组转二维数组
int **oneToTwo(int *one, int row, int col)
{
    int **two = malloc(row * sizeof(int *));
    for (int i = 0; i < row; i++)
    {
        two[i] = (int *)malloc(col);
        // printf("%p %d\n",two[i],sizeof(two[i]));
        for (int j = 0; j < col; j++)
        {
            two[i][j] = one[i * col + j];
        }
    }
    return two;
}

// 二维数组转一维数组
int *twoToOne(int **two, int row, int col)
{
    int *one = malloc(row * col * sizeof(int));
    for (int i = 0; i < row; i++)
    {
        for (int j = 0; j < col; j++)
        {
            one[i * col + j] = two[i][j];
        }
    }
    return one;
}

int main()
{
    int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
    int row = 3, col = 3;

    int **two = oneToTwo(a, row, col);
    printf("二维数组遍历:\n");
    for (int i = 0; i < row; i++)
    {
        for (int j = 0; j < col; j++)
        {
            printf("%d ", two[i][j]);
        }
        printf("\n");
    }

    int *one = twoToOne(two, row, col);
    printf("一维数组遍历:\n");
    for (int i = 0; i < row * col; i++)
    {
        printf("%d ", one[i]);
    }

    free(one);
    for (int i = 0; i < row; i++)
    {
        free(two[i]);
    }
    free(two);
    return 0;
}